﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MediaAdmin.Controllers
{
    [Authorize]
    public partial class LocatorController : BaseController
    {

        public ActionResult Upload(string locatorid, string assetid)
        {
            var model = new UploadModel() { LocatorId = locatorid, AssetId = assetid};
            var locator = Context.Locators.Where(x => x.Id == locatorid).SingleOrDefault();
            var uri = locator.Path.Substring(locator.Path.IndexOf("/asset-") + 1);
            model.ContainerName = uri.Substring(0, uri.IndexOf("?"));
            return View(model);
        }

        [HttpPost]
        public ActionResult Upload(string assetid)
        {
            var asset = Context.Assets.Where(x => x.Id == assetid).SingleOrDefault();
            asset.Publish();
            return RedirectToAction("Details", "Asset", new { id = assetid });
        }
        
        public ActionResult Play(string locatorid, string manifest)
        {
            var locator = Context.Locators.Where(x => x.Id == locatorid).SingleOrDefault();
            var model = new PlayModel();
            model.StreamingUrl = locator.Path + manifest + "/manifest(format=m3u8-aapl).m3u8";
            return View(model);
        }

        public ActionResult IosPlay(string locatorid, string manifest)
        {
            var locator = Context.Locators.Where(x => x.Id == locatorid).SingleOrDefault();
            var url = locator.Path + manifest + "/manifest(format=m3u8-aapl)";
            return RedirectPermanent(url);
        }

        public ActionResult SlvPlay(string locatorid, string manifest)
        {
            return View();
        }

        public ActionResult Download(string locatorid, string assetid)
        {
            var locator = Context.Locators.Where(x => x.Id == locatorid).SingleOrDefault();            
            var asset = Context.Assets.Where(x => x.Id == assetid).SingleOrDefault();
            var model = new List<DownloadModel>();
            foreach (var file in asset.Files)
            {
                var uriBuilder = new UriBuilder(locator.Path);
                uriBuilder.Path += "/" + file.Name;
                model.Add(new DownloadModel() { File = file.Name, Url = uriBuilder.ToString() });
            }

            return View(model);
        }
        
    }
}
